/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.mockexam.special.picture.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.utils.excel.annotation.ExcelField.Type;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.zx.mockexam.special.multiple.entity.TMockeSpecialMultiple;
import com.jeesite.modules.zx.mockexam.special.picture.entity.TmockexamSpecialPicture;
import com.jeesite.modules.zx.mockexam.special.picture.service.TmockexamSpecialPictureService;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;

/**
 * 模拟-专项考试-图片题表Controller
 * @author zpp
 * @version 2020-02-08
 */
@Controller
@RequestMapping(value = "${adminPath}/zx/mockexam/special/picture/tmockexamSpecialPicture")
public class TmockexamSpecialPictureController extends BaseController {

	@Autowired
	private TmockexamSpecialPictureService tmockexamSpecialPictureService;
	@Autowired
	private PostService postService;
	@Autowired
	private TquestionBankService tquestionBankService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public TmockexamSpecialPicture get(String id, boolean isNewRecord) {
		return tmockexamSpecialPictureService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("zx:mockexam:special:picture:view")
	@RequestMapping(value = {"list", ""})
	public String list(TmockexamSpecialPicture tmockexamSpecialPicture, Model model) {
		model.addAttribute("tmockexamSpecialPicture", tmockexamSpecialPicture);
		return "modules/zx/mockexam/special/picture/tmockexamSpecialPictureList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("zx:mockexam:special:picture:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<TmockexamSpecialPicture> listData(TmockexamSpecialPicture tmockexamSpecialPicture) {
		if (StringUtils.isBlank(tmockexamSpecialPicture.getParentCode())) {
			tmockexamSpecialPicture.setParentCode(TmockexamSpecialPicture.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(tmockexamSpecialPicture.getObjName())){
			tmockexamSpecialPicture.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tmockexamSpecialPicture.getObjPicture())){
			tmockexamSpecialPicture.setParentCode(null);
		}
		if (tmockexamSpecialPicture.getObjType() != null){
			tmockexamSpecialPicture.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tmockexamSpecialPicture.getRemarks())){
			tmockexamSpecialPicture.setParentCode(null);
		}
		if (tmockexamSpecialPicture.getObjExplain() != null){
			tmockexamSpecialPicture.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tmockexamSpecialPicture.getObjAnswer())){
			tmockexamSpecialPicture.setParentCode(null);
		}
		List<TmockexamSpecialPicture> list = tmockexamSpecialPictureService.findList(tmockexamSpecialPicture);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("zx:mockexam:special:picture:view")
	@RequestMapping(value = "form")
	public String form(TmockexamSpecialPicture tmockexamSpecialPicture, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tmockexamSpecialPicture = createNextNode(tmockexamSpecialPicture);
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		model.addAttribute("tmockexamSpecialPicture", tmockexamSpecialPicture);
		String objExplain=request.getParameter("objExplain");
		if(StringUtils.isNotBlank(objExplain)&&objExplain.equals("2")){
			TquestionBank quetionBank=new TquestionBank();
			quetionBank.setObjType(tmockexamSpecialPicture.getObjType());
			//查询单选
			List<TquestionBank> findList = tquestionBankService.findList(quetionBank);
			model.addAttribute("questionList",findList);
		}
		if(StringUtils.isNotBlank(objExplain)){
			return "modules/zx/mockexam/special/picture/tmockexamSpecialPictureForm"+objExplain;
		}
		return "modules/zx/mockexam/special/picture/tmockexamSpecialPictureForm";
	}
	@RequiresPermissions("zx:mockexam:special:picture:view")
	@RequestMapping(value = "questionForm")
	public String questionForm(TmockexamSpecialPicture tmockexamSpecialPicture, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tmockexamSpecialPicture = createNextNode(tmockexamSpecialPicture);
		String postCode=tmockexamSpecialPicture.getPost();
		TquestionBank quetionBank=new TquestionBank();
		quetionBank.setObjType(tmockexamSpecialPicture.getObjType());
		if(StringUtils.isNotBlank(postCode)){
			quetionBank.setPost(postCode);
		}else{
			quetionBank.getSqlMap().getWhere().and("post", QueryType.IS_NULL, null);
		}
		//查询单选
		List<TquestionBank> findList = tquestionBankService.findList(quetionBank);
		Post post = new Post();
		model.addAttribute("questionList",findList);
		model.addAttribute("postList", postService.findList(post));
		model.addAttribute("tmockexamSpecialPicture", tmockexamSpecialPicture);
		String objExplain=request.getParameter("objExplain");
		if(StringUtils.isNotBlank(objExplain)){
			return "modules/zx/mockexam/special/picture/tmockexamSpecialPictureForm"+objExplain;
		}
		return "modules/zx/mockexam/special/picture/tmockexamSpecialPictureForm";
	}
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("zx:mockexam:special:picture:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public TmockexamSpecialPicture createNextNode(TmockexamSpecialPicture tmockexamSpecialPicture) {
		if (StringUtils.isNotBlank(tmockexamSpecialPicture.getParentCode())){
			tmockexamSpecialPicture.setParent(tmockexamSpecialPictureService.get(tmockexamSpecialPicture.getParentCode()));
		}
		if (tmockexamSpecialPicture.getIsNewRecord()) {
			TmockexamSpecialPicture where = new TmockexamSpecialPicture();
			where.setParentCode(tmockexamSpecialPicture.getParentCode());
			TmockexamSpecialPicture last = tmockexamSpecialPictureService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				tmockexamSpecialPicture.setTreeSort(last.getTreeSort() + 30);
				tmockexamSpecialPicture.setId(IdGen.nextCode(last.getId()));
			}else if (tmockexamSpecialPicture.getParent() != null){
				tmockexamSpecialPicture.setId(tmockexamSpecialPicture.getParent().getId() + "001");
			}
		}
		// 以下设置表单默认数据
		if (tmockexamSpecialPicture.getTreeSort() == null){
			tmockexamSpecialPicture.setTreeSort(TmockexamSpecialPicture.DEFAULT_TREE_SORT);
		}
		return tmockexamSpecialPicture;
	}

	/**
	 * 保存模拟-专项考试-图片题表
	 */
	@RequiresPermissions("zx:mockexam:special:picture:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TmockexamSpecialPicture tmockexamSpecialPicture) {
		tmockexamSpecialPictureService.save(tmockexamSpecialPicture);
		return renderResult(Global.TRUE, text("保存模拟-专项考试-图片题表成功！"));
	}
	
	/**
	 * 停用模拟-专项考试-图片题表
	 */
	@RequiresPermissions("zx:mockexam:special:picture:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(TmockexamSpecialPicture tmockexamSpecialPicture) {
		TmockexamSpecialPicture where = new TmockexamSpecialPicture();
		where.setStatus(TmockexamSpecialPicture.STATUS_NORMAL);
		where.setParentCodes("," + tmockexamSpecialPicture.getId() + ",");
		long count = tmockexamSpecialPictureService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该模拟-专项考试-图片题表包含未停用的子模拟-专项考试-图片题表！"));
		}
		tmockexamSpecialPicture.setStatus(TmockexamSpecialPicture.STATUS_DISABLE);
		tmockexamSpecialPictureService.updateStatus(tmockexamSpecialPicture);
		return renderResult(Global.TRUE, text("停用模拟-专项考试-图片题表成功"));
	}
	
	/**
	 * 启用模拟-专项考试-图片题表
	 */
	@RequiresPermissions("zx:mockexam:special:picture:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(TmockexamSpecialPicture tmockexamSpecialPicture) {
		tmockexamSpecialPicture.setStatus(TmockexamSpecialPicture.STATUS_NORMAL);
		tmockexamSpecialPictureService.updateStatus(tmockexamSpecialPicture);
		return renderResult(Global.TRUE, text("启用模拟-专项考试-图片题表成功"));
	}
	
	/**
	 * 删除模拟-专项考试-图片题表
	 */
	@RequiresPermissions("zx:mockexam:special:picture:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TmockexamSpecialPicture tmockexamSpecialPicture) {
		tmockexamSpecialPictureService.delete(tmockexamSpecialPicture);
		return renderResult(Global.TRUE, text("删除模拟-专项考试-图片题表成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("zx:mockexam:special:picture:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<TmockexamSpecialPicture> list = tmockexamSpecialPictureService.findList(new TmockexamSpecialPicture());
		for (int i=0; i<list.size(); i++){
			TmockexamSpecialPicture e = list.get(i);
			// 过滤非正常的数据
			if (!TmockexamSpecialPicture.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getId(), e.getId()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("zx:mockexam:special:picture:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(TmockexamSpecialPicture tmockexamSpecialPicture){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		tmockexamSpecialPictureService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("zx:mockexam:special:picture:view")
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletRequest request,HttpServletResponse response) {
		TmockexamSpecialPicture entity=new TmockexamSpecialPicture();
		entity.setPage(new Page<>(request, response));
		Page<TmockexamSpecialPicture> findPage = tmockexamSpecialPictureService.findPage(entity);        
		List<TmockexamSpecialPicture> list = findPage.getList();
		for(TmockexamSpecialPicture single:list){
			Integer objExplain = single.getObjExplain();
			String dictLabel = DictUtils.getDictLabel("t_reading_explain", objExplain.toString(), "未定义");
			single.setStrExplain(dictLabel);
			String postCode = single.getPost();
			if(StringUtils.isNotBlank(postCode)){
				Post post= postService.get(postCode);
				single.setPostName(post.getPostName());
			}
			Integer category = single.getCategory();
			if(category!=null){
				String categoryName = DictUtils.getDictLabel("t_examination_category", category.toString(), "未定义");
				single.setCategoryName(categoryName);
			}
			Integer difficulty = single.getDifficulty();
			if(difficulty!=null){
				String difficultyName = DictUtils.getDictLabel("t_degree_difficulty", difficulty.toString(), "未定义");
				single.setDifficultyName(difficultyName);
			}
			Integer knowledgePointType = single.getKnowledgePointType();
			if(knowledgePointType!=null){
				String knowledgePointName = DictUtils.getDictLabel("t_knowledge_point_type", knowledgePointType.toString(), "未定义");
				single.setDifficultyName(knowledgePointName);
			}
		}
		String fileName = "多选题数据模板.xlsx";
		try(ExcelExport ee = new ExcelExport("多选题数据", TmockexamSpecialPicture.class, Type.IMPORT)){
			ee.setDataList(list).write(response, fileName);
		}
	}
	/**
	 * 导入用户数据
	 */
	@ResponseBody
	@RequiresPermissions("zx:mockexam:special:picture:edit")
	@PostMapping(value = "importData")
	public String importData(MultipartFile file, String updateSupport) {
		try {
			boolean isUpdateSupport = Global.YES.equals(updateSupport);
			String message = tmockexamSpecialPictureService.importData(file, isUpdateSupport);
			return renderResult(Global.TRUE, "posfull:"+message);
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
		}
	}
	/**
	 * 导出用户数据
	 */
	@RequiresPermissions("zx:mockexam:special:picture:view")
	@RequestMapping(value = "exportData")
	public void exportData(TmockexamSpecialPicture entity, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		
		List<TmockexamSpecialPicture> list = tmockexamSpecialPictureService.findList(entity);
		for(TmockexamSpecialPicture single:list){
			Integer objExplain = single.getObjExplain();
			String dictLabel = DictUtils.getDictLabel("t_reading_explain", objExplain.toString(), "未定义");
			single.setStrExplain(dictLabel);
			String postCode = single.getPost();
			if(StringUtils.isNotBlank(postCode)){
				Post post= postService.get(postCode);
				single.setPostName(post.getPostName());
			}
			Integer category = single.getCategory();
			if(category!=null){
				String categoryName = DictUtils.getDictLabel("t_examination_category", category.toString(), "未定义");
				single.setCategoryName(categoryName);
			}
			Integer difficulty = single.getDifficulty();
			if(difficulty!=null){
				String difficultyName = DictUtils.getDictLabel("t_degree_difficulty", difficulty.toString(), "未定义");
				single.setDifficultyName(difficultyName);
			}
			Integer knowledgePointType = single.getKnowledgePointType();
			if(knowledgePointType!=null){
				String knowledgePointName = DictUtils.getDictLabel("t_knowledge_point_type", knowledgePointType.toString(), "未定义");
				single.setDifficultyName(knowledgePointName);
			}
		}
		String fileName = "单选题数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("单选题数据", TmockexamSpecialPicture.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}
}